<?php
/**
 * BaseService
 *
 * PHP Version 5.4
 *
 * @author liuxu <liuxuphp@icesmart.cn>
 */
namespace Admin\Service;
use Think\Controller;
use Think\Upload;

/**
 * Class BaseService
 */
class BaseService extends Controller {

    /**
     * 上传文件
     */
    public function upload($file)
    {
        $upload = new Upload();
        $upload->maxSize = 1 * 1024 * 1024;  //设置附件上传大小
        $upload->exts = array('jpg','gif','png','jpeg'); //设置附件上传类型
        $upload->savePath  = '/Uploads/';
        $upload->rootPath  = './Images/';   //设置上传目录
        $upload->saveName = time().'_'.mt_rand();

        $result = $upload->uploadOne($file);
        if(!$result){
            $this->error($upload->getError());
        }else{
            return '/Images'.$result['savepath'].$result['savename'];
        }
    }
    /**
     * 上传多个文件
     *
     */
    public function uploadList($file, $size)
    {
        $upload = new Upload();
        $upload->maxSize = $size * 1024;  //设置附件上传大小
        $upload->exts = array('jpg','gif','png','jpeg'); //设置附件上传类型
        $upload->savePath  = '/Uploads/';
        $upload->rootPath  = './Images/';   //设置上传目录

        $imageFileRest = array();
        /*** 重新整理上传图片 ***/
        for($i = 0; $i < count($file['name']); $i++){
            $imageFileRest[$i]['name'] = $file['name'][$i];
            $imageFileRest[$i]['type'] = $file['type'][$i];
            $imageFileRest[$i]['tmp_name'] = $file['tmp_name'][$i];
            $imageFileRest[$i]['error'] = $file['error'][$i];
            $imageFileRest[$i]['size'] = $file['size'][$i];
        }

        $image = '';
        foreach($imageFileRest as $img){
            $upload->saveName = time().'_'.mt_rand();
            if($img['size'] > $upload->maxSize){
                $this->error('单张图片限制'.$size.'KB以内');
            }else{
                $result = $upload->uploadOne($img);
                if(!$result){
                    $this->error($upload->getError(),null,2);
                }else{
                    $image = $image . '/Images'.$result['savepath'].$result['savename']. ' ';
                }
            }
        }

        return $image;
    }
}